<template>
	<layout>
		<view class="daka">
			<view class="daka-top">
				<view @click="handleClick" :class="['daka-top-content', isCanDaka ? 'pulse-shadow' : 'stop-shadow' ]">
					<view class="daka-top-content-title">
						{{detail.id ? ( detail.hasClocked ? '已打卡' : '打卡') : '暂无打卡规则'}}
					</view>
					<text class="daka-top-content-time">{{ currentTime }}</text>
				</view>
			</view>
			<view class="daka-content" v-if="detail.id">
				<view class="daka-content-item">
					<text class="daka-content-item-label">打卡规则:</text>
					<text class="daka-content-item-value">{{detail.ruleName || ''}}</text>
				</view>
				<view class="daka-content-item">
					<text class="daka-content-item-label">打卡时段:</text>
					<text v-if="detail.startTime"
						class="daka-content-item-value">{{detail.startTime}}-{{detail.endTime}}</text>
				</view>
				<view class="daka-content-item">
					<text class="daka-content-item-label">打卡位置:</text>
					<text class="daka-content-item-value">{{detail.buildingName || ''}}</text>
				</view>
				<view class="daka-content-item">
					<text class="daka-content-item-label">是否需要拍照:</text>
					<text class="daka-content-item-value">{{detail.needPhoto ? '是' : '否'}}</text>
				</view>
				<uni-forms v-if="detail.needPhoto == 1" ref="baseForm" v-model="baseFormData" label-position="left">
					<uni-forms-item label="照片" name="attachList">
						<uni-file-picker v-model="baseFormData.attachList" @select="select"
							file-mediatype="image"></uni-file-picker>
					</uni-forms-item>
				</uni-forms>
			</view>
			<view class="daka-bottom">
				<view v-if="detail.id">
					<view v-if="isCanDaka && !detail.clockTime" class="daka-bottom-tips">
						<uni-icons type="checkbox-filled" color="blue" size="18"></uni-icons>已进入定位考勤范围
					</view>
					<view v-else-if="!isCanDaka && !detail.clockTime" class="daka-bottom-tips">
						<uni-icons type="info-filled" color="#bd0606" size="18"></uni-icons>当前不在打卡范围内
					</view>
					<view v-else class="daka-bottom-tips">
						<uni-icons :type="detail.clockTime ? 'checkbox-filled' : 'info-filled'"
							:color="detail.clockTime ? '#4CAF50' : '#bd0606'" size="18"></uni-icons>
						打卡时间：{{formatDateTime(detail.clockTime, 'YYYY-MM-DD HH:mm:ss')}}
					</view>
				</view>
			</view>
		</view>
	</layout>
</template>

<script>
	import {
		uploadImg,
		isCheckInRange,
		clockIn
	} from '@/api/system/user.js'

	import {
		formatDateTime
	} from '@/utils/common.js'

	import layout from '../../common/layout/layout.vue';
	export default {
		components: {
			layout
		},
		data() {
			return {
				currentTime: '',
				isCanDaka: false,
				detail: {
					needPhoto: true,
					isDaka: true,
				},
				baseFormData: {
					attachList: []
				},
				attachList: [],
				updateTimeTimer: null,
				isCanDakaTimer: null,
				lat: '',
				lng: '',
				loading: true,
			};
		},
		watch: {
			// lat: function(n, o) {
			// 	if (n !== o) {
			// 		this.getIsCanDaka()
			// 	}
			// },
			// lng: function(n, o) {
			// 	if (n !== o) {
			// 		this.getIsCanDaka()
			// 	}
			// }
		},
		beforeCreate() {

		},
		onUnload() {
			clearInterval(this.updateTimeTimer);
			clearInterval(this.isCanDakaTimer);
		},
		onLoad() {
			// this.getIsCanDaka();
			this.updateTime();
			if (this.isCanDakaTimer) {
				clearInterval(this.updateTimeTimer);
				clearInterval(this.isCanDakaTimer);
			}
			this.updateTimeTimer = setInterval(() => {
				this.updateTime();
			}, 2000); // 每秒更新时间

			this.isCanDakaTimer = setInterval(() => {
				// this.getIsCanDaka();
				this.getAddress(this.getIsCanDaka);
			}, 5000)
			this.getAuthorize();
		},
		methods: {
			formatDateTime,
			updateTime() {
				const now = new Date();
				const hours = this.formatTimePart(now.getHours());
				const minutes = this.formatTimePart(now.getMinutes());
				const seconds = this.formatTimePart(now.getSeconds());
				this.currentTime = `${hours}:${minutes}:${seconds}`;
			},
			formatTimePart(timePart) {
				return timePart < 10 ? `0${timePart}` : timePart; // 格式化为两位数字
			},
			getAuthorize() {
				uni.getSetting({
					success: (res) => {
						if (!res.authSetting['scope.userLocation']) {
							// 用户未授权，请求授权
							uni.authorize({
								scope: 'scope.userLocation',
								success: () => {
									// 用户同意授权，获取位置
									this.getAddress();
								},
								fail: () => {
									// 用户拒绝授权
									console.log('用户拒绝授权');
								}
							});
						} else {
							// 用户已授权，直接获取位置
							this.getAddress();
						}
					},
					fail: () => {
						// 获取权限设置失败
						console.log('获取权限设置失败');
					}
				})
			},
			getAddress(cb) {
				if (this.loading) {
					wx.showLoading({
					  title: '正在获取定位',
					})
				}
				
				const _this = this;
				uni.getLocation({
					type: 'wgs84',
					isHighAccuracy: true,
					success: function(res) {
						console.log(res)
						_this.lat = res.latitude;
						_this.lng = res.longitude;
						
						cb && cb();
					},
					fail: function(error) {
						console.error('获取位置失败：', error);
						wx.hideLoading();
					}
				});
			},
			getIsCanDaka() {
				isCheckInRange({
						lat: this.lat,
						lng: this.lng,
					})
					.then(data => {
						this.detail = data.data || {};
						this.isCanDaka = !!this.detail.canClock && !this.detail.hasClocked;
						
						this.loading = false;
						wx.hideLoading();
					})
			},
			handleClick() {
				if (this.detail.id && this.detail.canClock) {
					if (this.detail.needPhoto == 1 && !this.attachList.length) {
						uni.showToast({
							icon: 'fail',
							title: '需要上传图片'
						})
						return;
					}
					clockIn({
						ruleId: this.detail.id,
						attachmentList: this.attachList
					}).then(data => {
						this.isCanDaka = false;
						uni.showToast({
							title: '打卡成功'
						})
					})
				}
			},
			select(e) {
				console.log('选择文件：', e)
				const {
					tempFilePaths,
					tempFiles
				} = e;
				console.log(e)
				const _data = {
					name: 'file',
					filePath: tempFilePaths[0]
				}
				uploadImg(_data).then(response => {
					console.log(response)
					this.attachList.push({
						fileName: response.newFileName,
						filePath: response.url,
					})

				})
			},
		}
	}
</script>

<style lang="scss">
	.daka {
		background-color: #fff;
		height: 100vh;

		&-top {
			padding-top: 150rpx;
			padding-bottom: 150rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			&-content {
				width: 400rpx;
				height: 400rpx;
				border-radius: 50%;
				background: blue;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				flex-direction: column;
				transition: ease;

				&-title {
					font-weight: bold;
					font-size: 50rpx;
					padding-bottom: 40rpx;
				}

				&-time {
					font-size: 40rpx;
				}
			}
		}

		&-content {
			margin: 10rpx 40rpx 60rpx;

			&-item {
				display: flex;
				margin-bottom: 20rpx;

				&-label {
					// width: 120rpx;
					color: #606266;
					padding-right: 20rpx;
				}

				&-value {
					flex: 1;
				}
			}
		}

		&-bottom {
			text-align: center;

			&-tips {
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	@keyframes shadow-pulse {
		0% {
			box-shadow: 0 0 0 10rpx rgba(65, 165, 245, 0.2);
		}

		70% {
			box-shadow: 0 0 0 25rpx rgba(65, 165, 245, 0);
		}

		100% {
			box-shadow: 0 0 0 50rpx rgba(65, 165, 245, 0);
		}
	}

	.pulse-shadow {
		animation: shadow-pulse 2s infinite;
	}

	.stop-shadow {
		background: #ccc;
	}
</style>